package cn.kbyue.security.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * RSA 算法工具类
 *
 * @author xl
 * @date 2020/5/18 21:58
 */
public class RSALocalUtil {

    public static KeyPair createKey() {
        KeyPair rsa = SecureUtil.generateKeyPair("RSA");
        return rsa;
    }

    public static String encode(String data, PublicKey publicKey) {
        RSA rsa = new RSA(null, publicKey);
        return rsa.encryptBcd(data, KeyType.PublicKey, CharsetUtil.CHARSET_UTF_8);
    }

    public static String encode(String data, String publicKeyBase64) {
        RSA rsa = new RSA(null, publicKeyBase64);
        return rsa.encryptBcd(data, KeyType.PublicKey, CharsetUtil.CHARSET_UTF_8);
    }

    public static String decode(String encStr, PrivateKey privateKey) {
        RSA rsa = new RSA(privateKey, null);
        return rsa.decryptStrFromBcd(encStr, KeyType.PrivateKey, CharsetUtil.CHARSET_UTF_8);
    }

    public static String decode(String encStr, String privateKeyBase64) {
        RSA rsa = new RSA(Base64.decode(privateKeyBase64), null);
        return rsa.decryptStr(encStr, KeyType.PrivateKey, CharsetUtil.CHARSET_UTF_8);
    }

    public static void main(String[] args) {
        KeyPair key = RSALocalUtil.createKey();

        String encode = RSALocalUtil.encode("123456", key.getPublic());
        System.out.println(encode);
        String decode = RSALocalUtil.decode(encode, key.getPrivate());
        System.out.println(decode);

        RSALocalUtil.decode(encode, key.getPrivate());
    }

}
